<?php

class LoginController extends Controller
{
	public $defaultAction = 'login';
    public $layout='user';

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		if (Yii::app()->user->isGuest) {
			//cook同步登录
//			if ($_COOKIE['auth']){
//				$userCookie = json_decode(self::Decrypt($_COOKIE['auth'], 'sce7QSNwYpsVmenT'));
//				$password = self::Decrypt($userCookie->password, 'sce7QSNwYpsVmenT');
//
//				$transaction= Yii::app()->db->beginTransaction();//创建事务
//				$sql = "select `id`,`status`,c.itemname,b.first_name,b.last_name from tbl_users as a
//						left join tbl_profiles b on b.user_id = a.id
//						left join blog_authassignment c on c.userid = a.id
//						where username = '".$userCookie->user_name."' and password = '".md5($password)."'";
//				$userIn = Yii::app()->db->createCommand($sql)->queryRow();
//				$go = false;
//				$firstName = self::utf8Substr($userCookie->user_cn_name, 0, 1);
//				$lastName = self::utf8Substr($userCookie->user_cn_name, 1, strlen($userCookie->user_cn_name));
//				if (empty($userIn)){
//					try {
//						$sql = "insert into tbl_users(username,password,`status`) values('".$userCookie->user_name."','".md5($password)."','1')";
//						Yii::app()->db->createCommand($sql)->query();
//						$uid = Yii::app()->db->lastInsertID;
//
//						//tbl_profiles
//						$sqlProfile = "insert into tbl_profiles(user_id,first_name,last_name) values('$uid','$firstName','$lastName')";
//						Yii::app()->db->createCommand($sqlProfile)->query();
//
//						//blog_authassignment
//						$sqlSsign = "insert into blog_authassignment(itemname,userid) values('Poster','$uid')";
//						Yii::app()->db->createCommand($sqlSsign)->query();
//
//						$transaction->commit(); //提交事务
//						$go = true;
//					}catch (Exception $e) {
//					    $transaction->rollback();
//					}
//				}else{
//					try {
//						$uid = $userIn['id'];
//						if ($userIn['status'] != 1){
//							$sql = "update tbl_users set `status` = '1' where id = '$uid'";
//							Yii::app()->db->createCommand($sql)->query();
//						}
//						if (empty($userIn['itemname'])){
//							$sqlSsign = "insert into blog_authassignment(itemname,userid) values('Poster','$uid')";
//							Yii::app()->db->createCommand($sqlSsign)->query();
//						}
//						if (empty($userIn['first_name'])){
//							$sqlProfile = "insert into tbl_profiles(user_id,first_name,last_name) values('$uid','$firstName','$lastName')";
//							Yii::app()->db->createCommand($sqlProfile)->query();
//						}
//						$transaction->commit(); //提交事务
//						$go = true;
//					}catch (Exception $e) {
//					    $transaction->rollback();
//					}
//				}
//				if ($go === true){
//					$_POST['UserLogin']['username'] = $userCookie->user_name;
//					$_POST['UserLogin']['password'] = $password;
//					$_POST['UserLogin']['rememberMe'] = '0';
//				}
//			}
			//end
			
			$model=new UserLogin;
			// collect user input data
			if(isset($_POST['UserLogin']))
			{
				$model->attributes=$_POST['UserLogin'];
				// validate user input and redirect to previous page if valid
				if($model->validate()) {
					$this->lastViset();
					if (Yii::app()->user->returnUrl=='/index.php'){
                        if(Yii::app()->user->isSuperuser){
                            $this->redirect(Yii::app()->controller->module->returnUrl);
                        }else{
                            $this->redirect(array('/imgs/get_google_code'));
                        }
                    }
					else
						$this->redirect(Yii::app()->user->returnUrl);
				}
			}
			// display the login form
			$this->render('/user/login',array('model'=>$model));
		} else{
            if(Yii::app()->user->isSuperuser){
                $this->redirect(Yii::app()->controller->module->returnUrl);
            }else{
                $this->redirect(array('/imgs/get_google_code'));
            }
        }

	}
	
	private function lastViset() {
		$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
		$lastVisit->lastvisit = time();
		$lastVisit->save();
	}
	
	//解密
    public static function Decrypt($txtStream,$keyWord) {
        $lockstream = 'st=lDEFABCNOPyzghi_jQRST-UwxkVWXYZabcdef+IJK67nopqr89LMmGH012345uv';
        $lockLen = strlen($lockstream);
        $txtLen = strlen($txtStream);
        $randomLock = $txtStream[$txtLen - 1];
        $lockCount = strpos($lockstream,$randomLock);
        $keyWord = md5($keyWord.$randomLock);
        $txtStream = substr($txtStream,0,$txtLen-1);
        $tmpStream = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txtStream); $i++) {
            $k = $k == strlen($keyWord) ? 0 : $k;
            $j = strpos($lockstream,$txtStream[$i]) - $lockCount - ord($keyWord[$k]);
            while ($j < 0) {
                $j = $j + ($lockLen);
            }
            $tmpStream .= $lockstream[$j];
            $k++;
        }
        return base64_decode($tmpStream);
    }
    
    //utf8 字符串截取
    function utf8Substr($str, $from, $len)
    {
    	return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
    }

}